package com.ship.common.core.utils;

import ognl.Ognl;
import ognl.OgnlException;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 31463
 */
public class BeanUtils {

	public  static void copyProperties(Object source, Object target, String[] properties,String[] ignoreProperties){
		if(properties != null && properties.length > 0){
			org.springframework.beans.BeanUtils.copyProperties(target, source, properties);
		}
		org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties);
	}
	public  static void copyPropertiesWithoutNull(Object source, Object target, String[] properties,String[] ignoreProperties){
		List<String> ignorePropertiesList = new ArrayList<String>();
		if(ignoreProperties != null){
			for (String string : ignorePropertiesList) {
				ignorePropertiesList.add(string);
			}
		}
		Class<?> c = source.getClass();
		while(!c.equals(Object.class)){
			Field[] fields = c.getDeclaredFields();
			for (Field field : fields) {
				try {
					Object value = Ognl.getValue(field.getName(), source);
					if(value == null){
						ignorePropertiesList.add(field.getName());
					}
				} catch (OgnlException e) {
				}
			}
			c = c.getSuperclass();
		}
		copyProperties(source, target, null, ignorePropertiesList.toArray(new String[]{}));
	}
	
	public static Object getValue(Object root, String path) throws OgnlException {
		return Ognl.getValue(path, root);
	}
	
	public static void setValue(Object root, String path, Object value) throws OgnlException {
		Ognl.setValue(path, root, value);
	}
}
